package com.xz.supplierOrder.service.impl;

import com.xz.common.exception.ServiceException;
import com.xz.supplierOrder.domain.SupplierOrder;
import com.xz.supplierOrder.dto.SupplierOrderDto;
import com.xz.supplierOrder.enums.SupplierOrderTypeEnum;
import com.xz.supplierOrder.service.ISupplierOrderTypeFactoryService;
import com.xz.supplierOrder.service.ISupplierOrderTypeProcessorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service("orderTypeFactoryServiceImpl")
public class SupplierOrderTypeFactoryServiceImpl implements ISupplierOrderTypeFactoryService {

  @Autowired
  Map<String, ISupplierOrderTypeProcessorService> thirdPartSystemSyncServices = new ConcurrentHashMap<>();

  /**
   * 校验单据
   * @param supplierOrder （贸易中间商）单据商品
   */
  @Override
  public void verifyFields(SupplierOrderDto supplierOrder) {
    //根据枚举类型中的服务名称获取对应服务调用对应的方法
    String serviceName = getSupplierOrderTypeEnum(supplierOrder.getOrderType()).getServiceName();
    thirdPartSystemSyncServices.get(serviceName).verifyFields(supplierOrder);
  }

  /**
   * 提交单据
   * @param supplierOrder （贸易中间商）单据商品
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void submitOrder(SupplierOrder supplierOrder) {
    //根据枚举类型中的服务名称获取对应服务调用对应的方法
    String serviceName = getSupplierOrderTypeEnum(supplierOrder.getOrderType()).getServiceName();
    thirdPartSystemSyncServices.get(serviceName).submitOrder(supplierOrder);
  }

  /**
   * 冲红单据
   * @param supplierOrder （贸易中间商）单据商品
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void reversalOrder(SupplierOrder supplierOrder) {
    //根据枚举类型中的服务名称获取对应服务调用对应的方法
    String serviceName = getSupplierOrderTypeEnum(supplierOrder.getOrderType()).getServiceName();
    thirdPartSystemSyncServices.get(serviceName).reversalOrder(supplierOrder);
  }

  /**
   * 获取枚举类
   *
   * @param orderType
   * @return
   */
  private SupplierOrderTypeEnum getSupplierOrderTypeEnum(Integer orderType) {
    SupplierOrderTypeEnum enums = SupplierOrderTypeEnum.valOf(orderType);
    if (null == enums) {
      throw new ServiceException("操作失败，单据类型不存在");
    }
    return enums;
  }
}
